//
//  CZStatusListViewModel.swift
//  WeiBO28
//
//  Created by 飞奔的羊 on 16/5/13.
//  Copyright © 2016年 itcast. All rights reserved.
//

import UIKit

class CZStatusListViewModel: NSObject {
	var statusList: [CZStatusViewModels]?
	//isPillUp 是否上啦加载
	func requestStatus(isPillUp: Bool, complete: (isSuccess: Bool, message: String) ->()){

		//上啦加载使用的默认 maxID
		var maxID: Int64 = 0
		//下拉刷新使用的默认值
		var sinceId: Int64 = 0
		if isPillUp {
			//代表上啦加载更多,去数组最后一条 id
			maxID = self.statusList?.last?.status?.id ?? 0
			if maxID > 0 {
    //去除重复的微博数据
				maxID -= 1
			}
			
		} else {
		//下拉刷新要取数组里面第一条数据的 id
		sinceId = statusList?.first?.status?.id ?? 0
		}
		CZNetWorkTools.sharedTools.requestStatus(CZUserAccountViewModel.shareUserAccount.accessToken!, maxId: maxID, sinceId: sinceId) { (response, error) in
			var message: String = "没有加载到数据"
			
			if error != nil {
				print("网络请求异常")
				complete(isSuccess: false, message: message)
				return
			}
			guard let dic = response as? [String: AnyObject] else {
				complete(isSuccess: false, message: message)
				return
			}
			
			
			guard let statusesArray = dic["statuses"] as? [[String: AnyObject]] else {
				print("不是一个正确的json格式")
				complete(isSuccess: false, message: message)
				return
			}
			
			var tempArray = [CZStatusViewModels]()
			for value in statusesArray
			{
				let status = CZStatus(dic: value)
				//  通过status模型转成我们需要viewModel
				let statusViewModel = CZStatusViewModels(status: status)
				tempArray.append(statusViewModel)
				
			}
			//判断 status 是否为 nil, 如果为 nil 进行初始化
			if self.statusList == nil
			{
			self.statusList = [CZStatusViewModels]()
			}
			if isPillUp {
			//追加数据
//				self.statusList! += tempArray
				self.statusList = self.statusList! + tempArray
			
			} else {
				//不是上啦加载
			self.statusList = tempArray + self.statusList!
			}
			
//			dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), { () in
//				
//			
//			})
			let count = tempArray.count
			if count > 0 {
			message = "加载了\(count)条微博数据"
			
			}
			complete(isSuccess: true, message: message)
			
			
			

			
		}
	
	}
	
}
